package com.notary.util;

import cn.hutool.json.JSONObject;
import com.notary.entity.SysUser;
import com.notary.exception.BusinessException;
import io.jsonwebtoken.*;
import lombok.experimental.UtilityClass;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ldh
 * @Date: 2019/1/8 10:58
 */
@UtilityClass
public class JwtUtil {

    public static final String TOKEN_HEADER = "Authorization";

    public static final String TOKEN_PREFIX = "Bearer ";

    public static final String JWT_SECRET = "banzheng_secret";

    public static final String SUBJECT = "test";

    public static final String JWT_ISSUER = "刘德华";

    public static final int JWT_TTL = 60 * 60 * 1000 * 24 * 30;


    public static String createJWT(String id, String issuer, String subject, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Map<String, Object> claims = new HashMap<>();
        JwtBuilder builder = Jwts.builder() // 这里其实就是new一个JwtBuilder，设置jwt的body
                .setClaims(claims)          // 如果有私有声明，一定要先设置这个自己创建的私有的声明，这个是给builder的claim赋值，一旦写在标准的声明赋值之后，就是覆盖了那些标准的声明的
                .setId(id)                  // 设置jti(JWT ID)：是JWT的唯一标识，根据业务需要，这个可以设置为一个不重复的值，主要用来作为一次性token,从而回避重放攻击。
                .setIssuedAt(now)           // iat: jwt的签发时间
                .setIssuer(issuer)          // issuer：jwt签发人
                .setSubject(subject)        // sub(Subject)：代表这个JWT的主体，即它的所有人，这个是一个json格式的字符串，可以存放什么userid，roldid之类的，作为什么用户的唯一标志。
                .signWith(signatureAlgorithm, JWT_SECRET); // 设置签名使用的签名算法和签名使用的秘钥
        // 设置过期时间
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }


    public static String createJWT(SysUser user, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getUserId());
        claims.put("username", user.getUsername());
        claims.put("headImg", user.getHeadImg());
        claims.put("nickName", user.getNickName());
        claims.put("roleId", user.getRoleName());
        claims.put("notaryId", user.getNotaryId());
        claims.put("officeCode", user.getOfficeCode());
        claims.put("notaryName", user.getNotaryName());
        //    claims.put("authorities", user.getAuthorities());
        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)
                .setIssuer(JWT_ISSUER)
                .setSubject(SUBJECT)
                .signWith(signatureAlgorithm, JWT_SECRET);
        // 设置过期时间
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }


    public static Claims parseJWT(String jwt) {
        Claims claims = Jwts.parser()
                .setSigningKey(JWT_SECRET)
                .parseClaimsJws(jwt).getBody();
        return claims;
    }


    public static Claims validateJWT(String jwt) {
        try {
            Claims claims = Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(jwt).getBody();
            return claims;
        } catch (MalformedJwtException e) {
            throw new BusinessException("token格式有误");
        } catch (ExpiredJwtException e) {
            throw new BusinessException("token已过期");
        } catch (SignatureException e) {
            throw new BusinessException("token密钥错误");
        }

    }

    /**
     * 获取用户名
     *
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(token).getBody();
            return claims.get("username").toString();
        } catch (MalformedJwtException e) {
            throw new BusinessException("token格式有误");
        } catch (ExpiredJwtException e) {
            throw new BusinessException("token已过期");
        } catch (SignatureException e) {
            throw new BusinessException("token密钥错误");
        }
    }

    /**
     * 获取用户角色
     *
     * @param token
     * @return
     */
    public static String getUserRole(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(token).getBody();
            return claims.get("role").toString();
        } catch (MalformedJwtException e) {
            throw new BusinessException("token格式有误");
        } catch (ExpiredJwtException e) {
            throw new BusinessException("token已过期");
        } catch (SignatureException e) {
            throw new BusinessException("token密钥错误");
        }

    }

    /**
     * 获取用户权限
     *
     * @param token
     * @return
     */
    public static Collection<String> getAuthorities(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(token).getBody();
            return (Collection<String>) claims.get("authorities");
        } catch (MalformedJwtException e) {
            throw new BusinessException("token格式有误");
        } catch (ExpiredJwtException e) {
            throw new BusinessException("token已过期");
        } catch (SignatureException e) {
            throw new BusinessException("token密钥错误");
        }

    }

    /**
     * 是否过期
     *
     * @param token
     * @return
     */
    public static boolean isExpiration(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(token).getBody();
            return claims.getExpiration().before(new Date());
        } catch (MalformedJwtException e) {
            throw new BusinessException("token格式有误");
        } catch (ExpiredJwtException e) {
            throw new BusinessException("token已过期");
        } catch (SignatureException e) {
            throw new BusinessException("token密钥错误");
        }
    }


    public static void main(String[] args) {
//        String token = createJWT("123", "user", "{\"userId\":\"123\",\"userName\":\"驱蚊器\"}", 60 * 1000);
//        System.out.println(token);
//        Claims claims = parseJWT(token);
//        System.out.println(claims);
//        System.out.println(claims.getSubject());
//        System.out.println(parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJ1c2VySWRcIjpcIjEyM1wiLFwidXNlck5hbWVcIjpcIumpseiaiuWZqFwifSIsImlzcyI6InVzZXIiLCJleHAiOjE1OTYxNjY1MjksImlhdCI6MTU5NjE2NjQ2OSwianRpIjoiMTIzIn0.wLs4ksBrU2A49tPL9-BKJdgl4nNZUjvS90nK16t2sQo"));
        String appId = "0SgSM8od";
        String appSecret = "FlIzeElovDFTEI4S";
        long ts = System.currentTimeMillis();
        String nonce = DigestUtils.md5Hex(System.currentTimeMillis() + "");
        String signSrc = "nonce" + nonce + "ts" + ts + "appId" + appId + "appSecret" + appSecret;
        String sign = DigestUtils.md5Hex(signSrc);
        JSONObject body = new JSONObject();
        body.put("appId", appId);
        body.put("sign", sign);
        body.put("nonce", nonce);
        body.put("ts", ts);
        System.out.println(body.toString());
    }
}
